package cn.com.vs.utils;

import javax.sql.DataSource;

import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import cn.com.vs.DBManager;

public class DBUtils {

	public interface SqlBlock<T, R> {
	    R invoke(T arg);
	}
	
	SqlSessionFactory sqlSessionFactory = null;
	
	protected DBUtils(){
		DataSource dataSource = DBManager.getInstance().getDatasource();
		TransactionFactory transactionFactory = new JdbcTransactionFactory();
		Environment environment = new Environment("nk", transactionFactory, dataSource);
		Configuration configuration = new Configuration(environment);
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
	}
	
	private static DBUtils inst = null;
	
	public static void init(SqlSessionFactory factory){
		inst = new DBUtils();
		inst.sqlSessionFactory = factory;
	}
	
	public static SqlSession getSqlSession(){
		return inst.sqlSessionFactory.openSession(true);
	}
	
	public static SqlSession getSqlSession(boolean autoCommit){
		return inst.sqlSessionFactory.openSession(autoCommit);
	}
	
	public static Object execute( SqlBlock<Object,SqlSession> block,boolean autoCommit ){
		SqlSession session = getSqlSession(autoCommit);
		try{
			return block.invoke(session);
		}finally{
			session.close();
		}
	}
}
